package com.jboost.modules.app.service.strategry.xmallure;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.common.util.JSONUtil;
import com.jboost.modules.app.constant.*;
import com.jboost.modules.app.dto.*;
import com.jboost.modules.system.entity.AJdySyncData;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

//@Service(value = "xmAllureOrderQuery")
@Slf4j
public class XmAllureOrderQuery extends AbstractXmAllureUser<JsonObject, Boolean> {


    public String getAppId(){
        return "654318875348639588ec98ac";
    }
    public XMUserReqDto queryCustomerDetailInfo(String id) throws IOException {
        String header = getHeader("company");
        Map map = new HashMap();
        map.put("company_id", Long.valueOf(id));
        map.put("format", 0);
        HttpHeaders newHeaders = new HttpHeaders();
        newHeaders.set("Authorization", "Bearer " + header);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(customerDetailUrl+getParams(map)).addHeader("Authorization","Bearer " + header).get()
                .build();
        Response execute = client.newCall(request).execute();
        // String custmoerDetailResponse = HttpRestUtils.get(customerDetailUrl+getParams(map), map, newHeaders);
        // log.info("custmoerDetailResponse"+custmoerDetailResponse);
        String body = execute.body().string();
        CustomerDetailInfo customerDetailInfo =  JSONUtil.fromJson(body, CustomerDetailInfo.class);
        XMUserReqDto xmUserReqDto = buidXMUserReqDto1(customerDetailInfo);
        return xmUserReqDto;
    }

    private XMUserReqDto buidXMUserReqDto1(CustomerDetailInfo customerDetailInfo) {
        XMUserReqDto xmUserReqDto = new XMUserReqDto();
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CustomersBean> customers = data.getCustomers();
        //基本资料
        buildXmUserReqDtoBaseData(xmUserReqDto, customerDetailInfo);
        HashMap<String, List<XMUserReqDto.ContactBean>> hashMap = Maps.newHashMap();
        hashMap.put("value",new ArrayList<>());
        xmUserReqDto.setContact(hashMap);
        //运营联系人
        buildXmUserReqDtoData(xmUserReqDto.getContact().get("value"), customers);
        return xmUserReqDto;
    }
    @Async()
    public BaseResult<Boolean> invokeStrategy() throws Exception {
while (true) {
    log.info("开始批量查询客户数据");
    String header = null;
    try {
        header = getHeader("opportunity");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    List<String> ids = Lists.newArrayList();
    try {
        queryAndPush(header, 1, ids);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    Thread.sleep(1000000);
}
    }


    public void queryAndPush(String header, Integer index, List<String> ids) throws Exception {
        HashMap<String, Object> paramMap = Maps.newHashMap();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramMap.put("start_index", index);
//        Date date = new Date();
//        Date from = DateUtils.addMonths(date, -1);
//        paramMap.put("start_time",simpleDateFormat.format(from));
//        paramMap.put("end_time",simpleDateFormat.format(date));
        paramMap.put("count", 1000);
        paramMap.put("start_time", DateUtil.format(DateUtils.addDays(new Date(),-3),"yyyy-MM-dd HH:mm:ss"));
        paramMap.put("end_time", DateUtil.format(DateUtils.addDays(new Date(),3),"yyyy-MM-dd HH:mm:ss"));
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + header);

//        String s = HttpRestUtils.get("https://api-sandbox.xiaoman.cn/v1/company/fields", Maps.newHashMap(), headers);
//        System.out.println(s);
        //String custmorResponse = HttpRestUtils.get(customersUrl, paramMap, headers);
        OkHttpClient cclient = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url(orderUrl + getParams(paramMap)).addHeader("Authorization", "Bearer " + header).get()
                .build();
        Response execute1 = cclient.newCall(request1).execute();
        String custmorResponse = execute1.body().string();
        XmsjList customerInfo = JSONUtil.fromJson(custmorResponse, XmsjList.class);
        customerInfo.getData().getList().forEach(e -> {
            if (Objects.equals("13735892556", e.getStage())) {
                Map map = new HashMap();
                map.put("opportunity_id", e.getOpportunity_id());
                try {
                    HttpHeaders newHeaders = new HttpHeaders();
                    newHeaders.set("Authorization", "Bearer " + header);
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(orderDetailUrl + getParams(map)).addHeader("Authorization", "Bearer " + header).get()
                            .build();
                    Response execute = client.newCall(request).execute();
                    // String custmoerDetailResponse = HttpRestUtils.get(customerDetailUrl+getParams(map), map, newHeaders);
                    // log.info("custmoerDetailResponse"+custmoerDetailResponse);
                    String body = execute.body().string();
                    XmSJ customerDetailInfo = JSONUtil.fromJson(JSONUtil.fromJson(body, HashMap.class).get("data").toString(), XmSJ.class);

                    AJdySyncData sysUserDepart = gcDataMapper.selectById(e.getOpportunity_id() + "");
                    if (Objects.isNull(sysUserDepart)) {
                        addCustomer(customerDetailInfo);
                    } else {
                        updateCustomer(sysUserDepart, customerDetailInfo);
                    }
                    ids.add(e.getOpportunity_id() + "");

                } catch (Exception ex) {
                    log.error("查询订单{}数据失败", e.getOpportunity_id());
                }
            }
        });

    }

    public static String getParams(Map<String, Object> params) {
        StringBuffer sb = new StringBuffer("?");
        if (Objects.nonNull(params)) {
            for (Map.Entry<String, Object> item : params.entrySet()) {
                Object value = item.getValue();
                if (Objects.nonNull(value)) {
                    sb.append("&");
                    sb.append(item.getKey());
                    sb.append("=");
                    sb.append(value);
                }
            }
            return sb.toString();
        } else {
            return "";
        }
    }


    private void updateCustomer(AJdySyncData sysUserDepart, XmSJ customerDetailInfo) throws IOException, ParseException {
        HashMap<String, Object> param = getParam();
        XmOrderReqDto xmUserReqDto = buidXMUserReqDto(customerDetailInfo);
        param.put("data", xmUserReqDto);
        xmUserReqDto.setCreate_time(null);
       // xmUserReqDto.setOrder_state(getParaMap("1.待处理"));
        param.put("is_start workflow",true);
        param.put("is start trigger",true);
        param.put("data_id", sysUserDepart.getDataType());
        String post = HttpRestUtils.post(update_api, param, jdyHeaders);
        sysUserDepart.setData("xm");
        gcDataMapper.updateById(sysUserDepart);
        log.info("表单修改结果{}", post);
    }

    private XmOrderReqDto buidXMUserReqDto(XmSJ data) throws IOException, ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat m_simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat mn_simpleDateFormat = new SimpleDateFormat("yyyyMM");
        XmOrderReqDto orderReqDto = new XmOrderReqDto();
        try {
        XMUserReqDto xmUserReqDto = queryCustomerDetailInfo(data.getCompany().getCompany_id()+"");
        orderReqDto.setOrder_id(getParaMap(data.getName()));
        orderReqDto.setXmsjid(getParaMap(data.getOpportunity_id()));
        orderReqDto.setOrder_no(getParaMap(data.getName()));
        orderReqDto.setCustomer_name(xmUserReqDto.getCustomer_name());
        orderReqDto.setCustomer_no(xmUserReqDto.getCustomer_no());

            orderReqDto.setCustomer_email(getParaMap(data.getCustomer().get(0).getEmail()));
            orderReqDto.setRecive_name(getParaMap(data.getCompany().getName()));
            //orderReqDto.setRecive_phone(getParaMap(data.getCompany()..getCustomer_phone()));
            //orderReqDto.setRecive_address(getParaMap(data.getCustomer_address()));
        }catch (Exception e){}
        orderReqDto.setCreate_time(getParaMap(new Date()));
        orderReqDto.setOrder_time(getParaMap(data.getCreate_time()));
        Date parse = simpleDateFormat.parse(data.getCreate_time());
        orderReqDto.setOrder_month(getParaMap(m_simpleDateFormat.format(parse)));
        orderReqDto.setOrder_month_no(getParaMap(mn_simpleDateFormat.format(parse)));
        orderReqDto.setAccount_date(getParaMap(data.getAccount_date()));
        orderReqDto.setCurrency(getParaMap(data.getCurrency()));
        orderReqDto.setProduct_total_amount(getParaMap(data.getAmount()));
        orderReqDto.setAmount(getParaMap(data.getAmount()));
        try {
        JdyReq jdyReq = new JdyReq();
        jdyReq.setApp_id(getAppId());
        jdyReq.setEntry_id("66160a516c2efa24fea9bb93");
        jdyReq.setLimit(100);
        jdyReq.setFields(Arrays.asList("_widget_1712720465508","_widget_1712720465507"));
        JdyReq.FilterBean filterBean = new JdyReq.FilterBean();
        filterBean.setRel("and");
        List<JdyReq.FilterBean.CondBean> cond = new ArrayList<>();
        JdyReq.FilterBean.CondBean a = new JdyReq.FilterBean.CondBean();
        a.setField("_widget_1712720465508");
        a.setType("text");
        a.setMethod("eq");
        a.setValue(Arrays.asList(data.getMain_user_info().getNickname()));
        cond.add(a);
        filterBean.setCond(cond);
        jdyReq.setFilter(filterBean);

            String s = jdyQueryAll(jdyReq);
            JSONArray jsonArray = (JSONArray) JSONUtil.fromJson(s, HashMap.class).get("data");
            if (jsonArray.size() > 0) {
                XmOrderPeople dataBean = JSONUtil.fromJson(JSONUtil.toJson(jsonArray.get(0)), XmOrderPeople.class);
                orderReqDto.set_widget_1692592506304(getParaMap(dataBean.get_widget_1712720465507().getUsername()));
            }
        } catch (IOException ex) {

        }

        return orderReqDto;
    }


    public String getFormId() {
        return "646adb8c16da3c00080da6b6";
    }

    private void buildXmUserReqDtoBaseData(XMUserReqDto xmUserReqDto, CustomerDetailInfo customerDetailInfo) {
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CompanyBean> company = data.getCompany();
        List<CustomerDetailInfo.DataBean.CompanyBean.FieldsBean> fieldsBeans = company.stream().flatMap(entry -> entry.getFields().stream()).collect(Collectors.toList());
        //fieldsBeans.addAll(customerDetailInfo.getData().getExternal_field_data());
        Map<String, String> fieldMap = fieldsBeans.stream().collect(Collectors.toMap(CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getId, CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getValue, (a, b) -> a));
        System.out.println(JSONUtil.toJson(fieldMap));
        xmUserReqDto.setCtreat_time(getParaMap(data.getArchive_time()));
        xmUserReqDto.setAddress(getParaMap(fieldMap.get("address")));
        xmUserReqDto.setCustomer_name(getParaMap(fieldMap.get("name")));
        xmUserReqDto.setCustomer_abbreviation(getParaMap(fieldMap.get("short_name")));
        String country = String.valueOf(getParaMap(fieldMap.get("country")));

        xmUserReqDto.setMonther_land(getParaMap(customerDetailInfo.getData().getCountry_name()));
        xmUserReqDto.setCustomer_no(getParaMap(customerDetailInfo.getData().getSerial_id()));
        List<XMUserReqDto.LogoBean> logoBeans = new ArrayList<>();
        XMUserReqDto.LogoBean logoBean = new XMUserReqDto.LogoBean();
        logoBean.setUrl(getParaMap(fieldMap.get("homepage")));
        logoBeans.add(logoBean);
        HashMap<String, List<XMUserReqDto.LogoBean>> hashMap = Maps.newHashMap();
        hashMap.put("value", logoBeans);
        xmUserReqDto.setLogo(hashMap);
        //xmUserReqDto.setFirst_area(StringUtils.isBlank(String.valueOf(fieldMap.get("4685536191540"))) ? null : getParaMap(filterFh(fieldMap.get("4685536191540"))));
        xmUserReqDto.setGroup(getParaMap(fieldMap.get("group_id")));
        xmUserReqDto.setCustomer_stage(getParaMap(fieldMap.get("trail_status")));
        xmUserReqDto.setCustomer_nature(getParaMap(fieldMap.get("biz_type")));
        xmUserReqDto.setCustomer_orign(getParaMap(fieldMap.get("origin")));
        xmUserReqDto.setCustomer_attribution(getParaMap(fieldMap.get("")));
        String cus_tag = customerDetailInfo.getData().getTag().stream().map(CustomerTag::getTag_name).collect(Collectors.joining("|"));
        xmUserReqDto.setProduct_customer_label(getParaMap(cus_tag));
        List<CustomerOwner> customerOwners = customerDetailInfo.getData().getOwner();
        //业务员
        List<XMUserReqDto.AffiliatedSalespersonBean> affiliatedSalespersonBeans = new ArrayList<>();
        XMUserReqDto.AffiliatedSalespersonBean affiliatedSalespersonBean = new XMUserReqDto.AffiliatedSalespersonBean();
        String name = "";
        for (CustomerOwner e :
                customerOwners) {
            affiliatedSalespersonBean = new XMUserReqDto.AffiliatedSalespersonBean();
            affiliatedSalespersonBean.setName(getParaMap(e.getName()));
            affiliatedSalespersonBean.setUsername(getParaMap(e.getNickname()));
            affiliatedSalespersonBeans.add(affiliatedSalespersonBean);
            name = e.getNickname();
        }
        xmUserReqDto.setAffiliated_salesperson(getParaMap(name));
        xmUserReqDto.setCustomer_label(getParaMap(fieldMap.get("cus_tag")));
        xmUserReqDto.setCustomer_nature(getParaMap(fieldMap.get("17995147088")));
        xmUserReqDto.setPhone(getParaMap(fieldMap.get("1990331804234")));
        xmUserReqDto.setHot_selling_series(getParaMap(fieldMap.get("1820018870213")));
        xmUserReqDto.setSurface_treatment(getParaMap(fieldMap.get("1820523514226")));
        xmUserReqDto.setRequired_profile_size(getParaMap(fieldMap.get("1990341612167")));
        xmUserReqDto.setApplication_scenario(getParaMap(fieldMap.get("1820034895295")));
        xmUserReqDto.setCustomer_focus(getParaMap(fieldMap.get("1820036315666")));
        xmUserReqDto.setSearch_fields(getParaMap(fieldMap.get("17385158304")));
        xmUserReqDto.setSearch_keyword_attributes(getParaMap(fieldMap.get("306672013382")));
        xmUserReqDto.setInquiry_type(getParaMap(fieldMap.get("306672013382")));
        xmUserReqDto.setFirst_inquiry_time(getParaMap(fieldMap.get("1575870621271")));
        xmUserReqDto.setBrowse_page(getParaMap(fieldMap.get("3457075506185")));
        xmUserReqDto.setBrowse_time(getParaMap(fieldMap.get("3457081849252")));
        xmUserReqDto.setDrainage_area(getParaMap(fieldMap.get("4685536191540")));
        xmUserReqDto.setAnnual_procurement_amount(getParaMap(fieldMap.get("annual_procurement")));
        xmUserReqDto.setPurchase_intention(getParaMap(fieldMap.get("intention_level")));
        xmUserReqDto.setLading_consignee(getParaMap(fieldMap.get("17995289702")));
        xmUserReqDto.setCompany_remarks(getParaMap(fieldMap.get("remark")));
        xmUserReqDto.setFirst_quest(getParaMap(fieldMap.get("4013377180063")));
        xmUserReqDto.setAnnual_procurement_volume(getParaMap(fieldMap.get("3144298072880")));
        xmUserReqDto.setImport_experience(getParaMap(fieldMap.get("3144323956870")));
        xmUserReqDto.setSales_city(getParaMap(fieldMap.get("1820374615887")));
        xmUserReqDto.setOrder_worry(getParaMap(fieldMap.get("4013469433675")));
        xmUserReqDto.setUser_feed_back(getParaMap(fieldMap.get("4013477508140")));
        xmUserReqDto.setUser_lost_why(getParaMap(fieldMap.get("18387648976")));
        xmUserReqDto.setUser_discount(getParaMap(fieldMap.get("1695297844587")));
        xmUserReqDto.setNew_old_platforms(getParaMap(fieldMap.get("20272197174")));
        xmUserReqDto.setFlow_in(getParaMap(fieldMap.get("22672416156")));
        xmUserReqDto.setProduct_id(getParaMap(fieldMap.get("306665134430")));
        xmUserReqDto.setProduct_line(getParaMap(fieldMap.get("9504965728")));
        xmUserReqDto.setSettlement_way(getParaMap(fieldMap.get("18364901310")));
        //年龄
        xmUserReqDto.setAge(getParaMap(fieldMap.get("18364901310")));

    }

    private Object filterFh(Object country) {
        String s = country.toString();

        String replaceAll = s.replace("[", "").replace("]", "");
        String s1 = replaceAll.replaceAll("\"", "");
        return s1;
    }

    private void buildXmUserReqDtoData(List<XMUserReqDto.ContactBean> contact, List<CustomerDetailInfo.DataBean.CustomersBean> customers) {
        for (CustomerDetailInfo.DataBean.CustomersBean e : customers) {
            List<CustomerDetailInfo.DataBean.CustomersBean.ContactBean> contact1 = e.getContact();
            if (CollectionUtil.isNotEmpty(contact1)) {
                for (CustomerDetailInfo.DataBean.CustomersBean.ContactBean b : contact1) {
                    XMUserReqDto.ContactBean contactBean = new XMUserReqDto.ContactBean();
                    contactBean.setContact_name(getParaMap(e.getName()));
                    contactBean.setContcat_email(getParaMap(e.getEmail()));
                    contactBean.setContact_platform(getParaMap(b.getType()));
                    contactBean.setContact_account(getParaMap(b.getValue()));
                    contactBean.setContact_position(getParaMap(e.getPost()));
                    contactBean.setContact_phone(getParaMap(CollectionUtil.isNotEmpty(e.getTel_list()) ? e.getTel_list().get(0).get(0) : null));
                    contact.add(contactBean);
                }
            } else {
                XMUserReqDto.ContactBean contactBean = new XMUserReqDto.ContactBean();
                contactBean.setContact_name(getParaMap(e.getName()));
                contactBean.setContcat_email(getParaMap(e.getEmail()));
                contactBean.setContact_position(getParaMap(e.getPost()));
                contactBean.setContact_phone(getParaMap(CollectionUtil.isNotEmpty(e.getTel_list()) ? e.getTel_list().get(0).get(0) : null));
                contact.add(contactBean);
            }
        }
        ;

    }

    private void addCustomer(XmSJ customerDetailInfo) throws IOException, ParseException {
        HashMap<String, Object> param = getParam();
        XmOrderReqDto xmUserReqDto = buidXMUserReqDto(customerDetailInfo);
        xmUserReqDto.setOrder_state(getParaMap("1.待处理"));
        param.put("data", xmUserReqDto);
        param.put("is_start_workflow",true);
        param.put("is_start_trigger",true);
        String post = HttpRestUtils.post(add_api, param, jdyHeaders);
        HashMap hashMap = JSONUtil.fromJson(post, HashMap.class);
        log.info("表单新增结果{}", post);
        AJdySyncData userDepart = new AJdySyncData();
        userDepart.setId(customerDetailInfo.getOpportunity_id() + "");
        userDepart.setDataType(((JSONObject) hashMap.get("data")).getString("_id"));
        userDepart.setData("xm");
        gcDataMapper.insert(userDepart);

    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
          invokeStrategy();
    }
}
